﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Interfaces.Data;

namespace Rodunu.Movies.Data
{
    public class StandardRepository<T> : IStandardRepsitory<T> where T : IStandardIdentifier
    {
        private static ISession _Session;

        #region IStandardRepsitory<T> Members

        public virtual void Create(T identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Save(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }

        public virtual T Find(int id)
        {
            _Session = DBHelper.GetCurrentSession();
            return (T)_Session.Load(typeof(T), id);
        }

        public IList<T> FindByBase(IStandardIdentifier identifiable)
        {
            //TODO: set this up for more custom dev
            return
                DBHelper.GetCurrentSession().CreateCriteria(typeof(T)).Add(Restrictions.Eq("ServerDetail", identifiable)).List
                    <T>();
        }

        public IList<T> FindAll()
        {
            return DBHelper.GetCurrentSession().CreateCriteria(typeof(T)).List<T>();
        }

        public void Delete(T identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Delete(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }

        public void Update(T identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Update(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }
        #endregion
    }
}
